import cv2
import numpy as np

filename = 'teachers_code/lena.bmp'
src = cv2.imread(filename, cv2.IMREAD_COLOR)
image = src
winname = 'adjust hsv'


def change_hsv(pos):
    global image
    dh = cv2.getTrackbarPos('H', winname) * 255 / 360
    ds = cv2.getTrackbarPos('S', winname) - 255
    dv = cv2.getTrackbarPos('V', winname) - 255
    hsv = cv2.cvtColor(src, cv2.COLOR_RGB2HSV_FULL)
    hsv = hsv.astype(np.float32)
    h, s, v = cv2.split(hsv)
    h = (h + dh) % 255
    s += ds
    s[v > 255] = 255
    s[s < 0] = 0
    v += dv
    v[v > 255] = 255
    v[v < 0] = 0
    hsv = cv2.merge((h, s, v))
    hsv = hsv.astype(np.uint8)
    image = cv2.cvtColor(hsv, cv2.cv2.COLOR_HSV2BGR_FULL)


def show():
    # 创建一个窗口
    cv2.namedWindow(winname)
    # 创建hsv滑杆
    cv2.createTrackbar('H', winname, 0, 360, change_hsv)
    cv2.createTrackbar('S', winname, 0, 512, change_hsv)
    # 因为OpenCV滑杆不支持负数，S滑杆只好以255位0
    cv2.setTrackbarPos('S', winname, 255)
    cv2.createTrackbar('V', winname, 0, 512, change_hsv)
    # 因为OpenCV滑杆不支持负数，S滑杆只好以255位0
    cv2.setTrackbarPos('V', winname, 255)
    while True:
        cv2.imshow(winname, image)
        key = cv2.waitKey(1)
        if key == ord(chr(27)):
            break
    cv2.destroyAllWindows()


show()
